<template>
    <div class="forum-container">
      <div class="forum-wrapper">
        <!-- 左侧内容区域 -->
        <div class="left-content">
          <!-- 顶部导航 -->
          <div class="top-nav">
            <div class="nav-tabs">
              <div 
                v-for="(tab, index) in tabs" 
                :key="index" 
                class="nav-tab" 
                :class="{ active: activeTab === tab.value }"
                @click="tabChange(tab.value)"
              >
                {{ tab.label }}
              </div>
            </div>
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索"
                @keyup.enter="searchForum"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
  
          <!-- 分类标签 -->
          <div class="category-tags">
            <div 
              v-for="(tag, index) in categoryTags" 
              :key="index" 
              class="category-tag" 
              :class="{ active: activeCategory === tag.value }"
              @click="categoryChange(tag.value)"
            >
              {{ tag.label }}
            </div>
          </div>
  
          <!-- 帖子列表 -->
          <div class="post-list" v-loading="loading">
            <div class="post-item" v-for="(post, index) in posts" :key="index" >
              <div class="post-header" @click="goForumDetail(post)">
                <div class="post-title" v-html="post.title"></div>
                <div class="post-tags" v-if="post.tags && post.tags.length">
                  <span class="tag" v-for="(tag, tagIndex) in post.tags" :key="tagIndex">{{ tag }}</span>
                </div>
              </div>
              <div class="post-content" @click="goForumDetail(post)">
                <div class="post-image" >
                  <img :src="post.img[0]" alt="帖子封面" />
                </div>
                <div class="post-text" v-html="post.content"></div>
              </div>
              <div class="post-footer">
                <div class="post-files" v-if="post.material && post.material.length">
                  <div class="file-item" v-for="(file, fileIndex) in post.material" :key="fileIndex">
                    <div class="file-info">
                      <div class="file-name">{{ file.name }}</div>
                      <div class="file-size">大小: {{ (file.size / 1024 / 1024).toFixed(2) }}MB</div>
                    </div>
                    <div class="download-btn" @click="downloadFile(file.url)">
                      <el-icon><Download /></el-icon>
                    </div>
                  </div>
                </div>
                <div class="post-meta">
                  <div class="post-time">{{ formatDate(post.create_time) }}</div>
                  <div class="post-actions">
                    <div class="action-item">
                      <img :src="post.is_like ? like : unLike" alt="点赞" @click="handleForumLikeIndex(post.id, post.is_like)" />
                      <span>{{ post.like }}</span>
                    </div>
                    <div class="action-item">
                      <img src="~@/static/comment.png" alt="点赞" />
                      <span>{{ post.comment }}条评论</span>
                    </div>
                    <!-- <div class="action-item">
                      <el-icon><Star /></el-icon>
                      <span>{{ post.likes }}</span>
                    </div> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
  
          <!-- 分页 -->
          <div class="pagination-container">
            <Pagination 
              :current-page="currentPage" 
              :total="totalPosts" 
              :page-size="pageSize"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
  
        <!-- 右侧内容区域 -->
        <div class="right-content">
          <!-- 用户信息 -->
          <div class="user-info-card">
            <div class="user-avatar">
                <!-- #18404B -->
                <!-- <div class="loginUsr" v-if="isLoggedIn"></div> -->
              <!-- <img  alt="用户头像" v-if="isLoggedIn" /> -->
            <!--   <div class="default-avatar" ></div> -->
            </div>
            <div class="user-details" v-if="isLoggedIn">
                <div class="user-left">
                    <div class="loginUsr">
                      <img :src="userInfo.avatar" alt="用户头像" />
                    </div>
                    <div class="user-loginInfo">
                        <div class="user-name">{{ userInfo.name }}</div>
                        <div class="user-status">努力学习的第{{ userInfo.days + 1 }}天</div>
                    </div>
                </div>

              <div class="user-stats">
                <div class="stat-item">
                  <div class="stat-label">获赞</div>
                  <div class="stat-value">{{ userInfo.likes }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">发帖</div>
                  <div class="stat-value">{{ userInfo.posts }}</div>
                </div>
              </div>
              <el-button type="primary" class="post-btn" @click="createNewPost">发帖</el-button>
            </div>
            <div class="login-prompt" v-else>
              <div class="prompt-text">登录后才能发帖</div>
              <el-button type="primary" class="login-btn" @click="goToLogin">登录</el-button>
            </div>
          </div>
  
          <!-- 热门资讯 -->
          <div class="hot-news-card">
            <div class="card-header">
              <div class="header-icon"></div>
              <h3 class="card-title">热门资讯帖</h3>
            </div>
            
            <!-- 分类标签 -->
            <div class="news-category-tabs">
              <div 
                v-for="(tab, index) in newsTabs" 
                :key="index" 
                class="news-tab" 
                :class="{ active: activeNewsTab === tab.value }"
                @click="handleNewsTabChange(tab.value)"
              >
                {{ tab.label }}
              </div>
            </div>
  
            <!-- 热门帖子列表 -->
            <div class="hot-post-list" v-loading="hotPostsLoading">
              <div class="hot-post-item" v-for="(post, index) in hotPosts" :key="index" @click="goForumDetail(post)">
                <div class="hot-post-title" v-html="post.title"></div>
                <div class="hot-post-meta">
                  <div class="meta-item">
                    <img :src="post.is_like ? like : unLike" alt="点赞" />
                    <span>{{ post.like || 0 }}</span>
                  </div>
                  <div class="meta-item">
                    <img src="~@/static/comment.png" alt="评论" />
                    <span>{{ post.comment || 0 }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { Search, Download, View, ChatDotRound, Star } from '@element-plus/icons-vue';
  import { handleForumList, handleForumLike } from '@/service/forum';
  import dayjs from 'dayjs';
  import Pagination from '@/components/Pagination.vue';
  import { ElMessage } from 'element-plus';
  import { useUserStore } from '@/stores/User';
  import avatar from '@/static/image.png';
  import like from '@/static/like.png';
  import unLike from '@/static/un_like.png';
  
  const router = useRouter();
  const userStore = useUserStore();
  
  // 用户登录状态
  const isLoggedIn = computed(() => userStore.isLoggedIn);
  const loading = ref(false);
  const hotPostsLoading = ref(false);
  
  // 用户信息
  const userInfo = computed(() => {
    return {
      name: userStore.personalDetailInfo?.username || '',
      days: calculateDays(),
      likes: userStore.personalDetailInfo?.postbar_like || 0,
      posts: userStore.personalDetailInfo?.postbar_num || 0,
      avatar: userStore.personalDetailInfo?.avatar || avatar
    };
  });
  
  // 计算用户注册天数
  const calculateDays = () => {
    if (!userStore.personalDetailInfo?.create_time) {
      return 0;
    }
    
    const createTime = new Date(userStore.personalDetailInfo.create_time * 1000);
    const currentTime = new Date();
    const timeDifference = currentTime.getTime() - createTime.getTime();
    const daysDifference = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
    
    return daysDifference > 0 ? daysDifference : 1;
  };
  
  // 顶部导航标签
  const tabs = ref([
    { label: '全部', value: 'all' },
    { label: 'GMAT', value: 'gmat' },
    { label: 'GRE', value: 'gre' },
    { label: 'EA', value: 'ea' }
  ]);
  const activeTab = ref('all');
  
  // 分类标签
  const categoryTags = ref([
    { label: '综合', value: 'comprehensive' },
    { label: '最新发布', value: 'latest' },
    { label: '最多点赞', value: 'most_liked' },
    { label: '只看发布', value: 'published_only' }
  ]);
  const activeCategory = ref('comprehensive');
  
  // 热门资讯标签
  const newsTabs = ref([
    { label: '全部', value: 'all' },
    { label: 'GMAT', value: 'gmat' },
    { label: 'GRE', value: 'gre' },
    { label: 'EA', value: 'ea' }
  ]);
  const activeNewsTab = ref('all');
  
  // 热门资讯的请求参数
  const hotPostsParams = ref({
    page: 1,
    rows: 5,
    sort: 0, // 按点赞数排序
    title: '',
    type: 0 // 全部项目
  });

  // 热门帖子数据
  const hotPosts = ref([]);
  
  // 搜索关键词
  const searchKeyword = ref('');
  
  // 分页数据
  const currentPage = ref(1);
  const pageSize = ref(10);
  const totalPosts = ref(100);
  const dataParams = ref({
    page: 1,
    rows: 10,
    sort: 0, // 综合排序
    title: '', // 搜索关键词，可以为空
    type: 0 // 全部项目
  });

  const formatDate = (date) => {
    return dayjs(date * 1000).format('YYYY-MM-DD');
  }

  const goForumDetail = (post) => {
    router.push(`/forumDetail/${post.id}`);
  }
  const tabChange = (tab) => {
    activeTab.value = tab;
    const type = tab === 'all' ? 0 : tab === 'gmat' ? 1 : tab === 'gre' ? 2 : tab === 'ea' ? 3 : 4;
    dataParams.value.type = type;
    getForumList()
  }

  const categoryChange = (category) => {
    activeCategory.value = category;
    const sort = category === 'comprehensive' ? 0 : category === 'latest' ? 1 : category === 'most_liked' ? 2 : category === 'published_only' ? 3 : 4;
    dataParams.value.sort = sort;
    getForumList()
  }

  const searchForum = () => {
    dataParams.value.title = searchKeyword.value;
    getForumList()
  }

  // 页码变化处理
  const handlePageChange = (page) => {
    currentPage.value = page;
    dataParams.value.page = page;
    getForumList()
  }

  const handleSizeChange = (size) => {
    pageSize.value = size;
    dataParams.value.rows = size;
    getForumList()
  }
  const posts = ref([]);
  
  // 跳转到登录页
  const goToLogin = () => {
    router.push('/login');
  };
  
  // 创建新帖子
  const createNewPost = () => {
    router.push('/forum/create');
  };
  
  // 下载文件
  const downloadFile = (url) => {
    if (!url) {
      ElMessage.error('文件不存在！');
      return;
    }
    
    // 创建一个隐藏的a标签用于下载
    const downloadLink = document.createElement('a');
    downloadLink.href = url;
    
    // 从URL中提取文件名，如果无法获取则使用默认名称
    const fileName = url.split('/').pop() || '下载文件';
    downloadLink.setAttribute('download', fileName);
    
    // 添加到body，触发点击，然后移除
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    
    ElMessage.success('开始下载文件');
  };
  
  // 点赞帖子
  const handleForumLikeIndex = (id, is_like) => {
    if (!isLoggedIn.value) {
      ElMessage.warning('请先登录后再操作');
      return;
    }
    
    // 调用点赞API
    handleForumLike({ logid:id, type: 1 }).then(res => {
      if (res.code === '000000') {
        // 找到对应帖子并更新点赞数
        const post = posts.value.find(item => item.id === id);
        if (post) {
          // 根据当前状态更新点赞数和状态
          if (is_like === 0) {
            // 未点赞，现在点赞
            post.like += 1;
            post.is_like = 1;
            // ElMessage.success('点赞成功');
          } else {
            // 已点赞，取消点赞
            post.like -= 1;
            post.is_like = 0;
            ElMessage.info('已取消点赞');
          }
        }
      } else {
        ElMessage.error(res.message || '操作失败');
      }
    }).catch(() => {
      ElMessage.error('操作失败');
    });
  };
  
  // 调用接口
  const getForumList = () => {
    loading.value = true;
    handleForumList(dataParams.value).then(res => {
      if(res.code === '000000') {
        // 处理返回数据
        posts.value = res.data.result;
        totalPosts.value = res.data.totalCount;
      }
      loading.value = false;
    }).catch(() => {
      loading.value = false;
    });
  };
  
  // 热门资讯标签变化处理
  const handleNewsTabChange = (tab) => {
    activeNewsTab.value = tab;
    const type = tab === 'all' ? 0 : tab === 'gmat' ? 1 : tab === 'gre' ? 2 : tab === 'ea' ? 3 : 4;
    hotPostsParams.value.type = type;
    // 保持sort参数不变，确保始终按点赞数排序
    hotPostsParams.value.sort = 2;
    getHotPostsList();
  }
  
  // 获取热门帖子列表
  const getHotPostsList = () => {
    hotPostsLoading.value = true;
    handleForumList(hotPostsParams.value).then(res => {
      if(res.code === '000000') {
        // 处理返回数据
        hotPosts.value = res.data.result;
      }
      hotPostsLoading.value = false;
    }).catch(() => {
      hotPostsLoading.value = false;
    });
  };
  
  onMounted(() => {
    // 可以在这里添加初始化逻辑，如获取帖子列表等
    getForumList()
    // 获取热门帖子列表
    getHotPostsList()
  });
  </script>
  
  <style scoped lang="scss">
  // 提取公共变量
  $primary-color: #126983;
  $text-color: #333;
  $light-text-color: #666;
  $border-color: #eee;
  $background-color: #ecf4f2;
  $card-background: #f9f9f9;
  $border-radius: 8px;
  $box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .forum-container {
    display: flex;
    justify-content: center;
    padding: 20px;
    background-color: $background-color;
    min-height: 100vh;
  }
  
  .forum-wrapper {
    width: 1175px; // 776 + 20 + 379 = 1175
    display: flex;
    gap: 20px;
  }
  
  // 左侧内容区域
  .left-content {
    width: 776px;
    background-color: #fff;
    border-radius: $border-radius;
    box-shadow: $box-shadow;
    padding: 20px;
  }
  
  // 右侧内容区域
  .right-content {
    width: 379px;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  // 顶部导航
  .top-nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .nav-tabs {
    display: flex;
    gap: 20px;
  }
  
  .nav-tab {
    font-size: 16px;
    cursor: pointer;
    padding: 5px 0;
    position: relative;
    
    &.active {
      color: $primary-color;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -2px;
        left: 0;
        width: 100%;
        height: 2px;
        background-color: $primary-color;
      }
    }
  }
  
  .search-box {
    width: 200px;
  }
  
  // 分类标签
  .category-tags {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
  }
  
  .category-tag {
    padding: 5px 15px;
    border-radius: 20px;
    background-color: #f0f0f0;
    font-size: 14px;
    cursor: pointer;
    
    &.active {
      background-color: $primary-color;
      color: #fff;
    }
  }
  
  // 帖子列表
  .post-list {
    margin-bottom: 20px;
  }
  
  .post-item {
    padding: 20px 0;
    border-bottom: 1px solid $border-color;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .post-header {
    margin-bottom: 15px;
    display:flex;
    align-items: center;
  }
  
  .post-title {
    font-size: 18px;
    font-weight: 500;
    margin-right: 10px;
    color: $text-color;
  }
  
  .post-tags {
    display: flex;
    gap: 10px;
  }
  
  .tag {
    padding: 2px 8px;
    background: #1269831A;
    color:#126983;
    border-radius: 4px;
    font-size: 12px;
    // color: $light-text-color;
  }
  
  .post-content {
    margin-bottom: 15px;
    display:flex;
  }
  
  .post-text {
    font-size: 14px;
    line-height: 1.6;
    color: $text-color;
    // margin-bottom: 15px;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .post-image {
    min-width: 95px;
    height: 76px;
    border-radius: 4px;

    background-color: #eee;

    margin-right:10px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    // margin-bottom: 15px;
  }
  
  .post-files {
    margin-bottom: 15px;
    display:flex;
    flex-wrap:wrap;
    gap:10px;
  }
  
  .file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    min-width:238.67px;
    border: 1px solid #CCCCCC;
    background-color: $card-background;
    border-radius: $border-radius;
    margin-bottom: 10px;
    
    &:last-child {
    //   margin-bottom: 0 !importa;
    }
  }
  
  .file-info {
    display: flex;
    flex-direction: column;
  }
  
  .file-name {
    font-size: 14px;
    margin-bottom: 5px;
  }
  
  .file-size {
    font-size: 12px;
    color: $light-text-color;
  }
  
  .download-btn {
    cursor: pointer;
    color: $primary-color;
    
    &:hover {
      opacity: 0.8;
    }
  }
  
  .post-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .post-time {
    font-size: 14px;
    color: $light-text-color;
  }
  
  .post-actions {
    display: flex;
    gap: 15px;
  }
  
  .action-item {
    display: flex;
    align-items: center;
    gap: 5px;
    color: $light-text-color;
    cursor: pointer;
    
    &:hover {
      color: $primary-color;
    }
    img {
      width: 16px;
      height: 16px;
    }
  }
  
  // 分页
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  // 用户信息卡片
  .user-info-card {
    background-color: #fff;
    border-radius: $border-radius;
    box-shadow: $box-shadow;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
//   .user-avatar {
//     width:54px;
//     height:54px;
//     border-radius: 50%;
//     // background-color: #eee;
//     margin-bottom: 15px;
//     // overflow: hidden;
    
//     img {
//       width: 100%;
//       height: 100%;
//       object-fit: cover;
//     }
//   }
  
  .default-avatar {
    width: 100%;
    height: 100%;
    background-color: #ddd;
  }
  
  .user-details {
    width: 100%;
    text-align: center;
    
  }
  
  .user-name {
    font-size: 18px;
    font-weight: 500;
    margin-bottom: 5px;
  }
  
  .user-status {
    font-size: 14px;
    color: $light-text-color;
    // margin-bottom: 15px;
  }
  
  .user-stats {
    display: flex;
    justify-content: space-between;
    padding:0px 20px;
    // gap: 20px;
    margin-bottom: 20px;
  }
  
  .stat-item {
    text-align: center;
    flex:1;
  }
  
  .stat-label {
    font-size: 14px;
    color: $light-text-color;
    margin-bottom: 5px;
  }
  
  .stat-value {
    font-size: 18px;
    font-weight: 500;
    color: $primary-color;
  }
  
  .post-btn {
    width: 100%;
    height:42px;
    background-color: $primary-color;
    border-color: $primary-color;
  }
  
  .login-prompt {
    width: 100%;
    text-align: center;
  }
  
  .prompt-text {
    font-size: 16px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .login-btn {
    width: 100%;
    background-color: $primary-color;
    border-color: $primary-color;
  }
  
  // 热门资讯卡片
  .hot-news-card {
    background-color: #fff;
    border-radius: $border-radius;
    box-shadow: $box-shadow;
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    position: relative;
  }
  
  .header-icon {
    width: 16px;
    height: 16px;
    background-color: $primary-color;
    margin-right: 10px;
  }
  
  .card-title {
    font-size: 18px;
    font-weight: 500;
  }
  
  .news-category-tabs {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    flex-wrap: wrap;
  }
  
  .news-tab {
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    
    &.active {
      background-color: $primary-color;
      color: #fff;
    }
  }
  
  .hot-post-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .hot-post-item {
    padding-bottom: 15px;
    border-bottom: 1px solid $border-color;
    
    &:last-child {
      border-bottom: none;
      padding-bottom: 0;
    }
  }
  
  .hot-post-title {
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 10px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    cursor: pointer;
    
    &:hover {
      color: $primary-color;
    }
  }
  
  .hot-post-meta {
    display: flex;
    gap: 15px;
  }
  
  .meta-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    color: $light-text-color;
    &:nth-child(2) {
      margin-left: 10px;
    }
    img {
      width: 16px;
      height: 16px;
      margin-right: 5px;
    }
  }
  .loginUsr{
    width:54px;
    height:54px;
    border-radius:50%;
    background-color:#18404B;
    img {
      width:100%;
      height:100%;
      object-fit: cover;
      border-radius:50%;
    }
    // height:100%;
  }
  .user-left{
        display: flex;
        align-items:center;
        padding:10px;
        margin-left:20px;
    }
    .user-loginInfo{
        display: flex;
        margin-left:20px;
    flex-direction: column;
    text-align: left;  
    
    }
  </style>